package face.pay.open.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.face.pay.WxApiConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: zkj
 * @Date: 2019/8/27 13:15
 * @Description:
 */
@Component
@Slf4j
public class CertficatesServer {

    private  final static  String domain = "api.mch.weixin.qq.com";

    private  final static  String urlSuffix = "/risk/getcertficates";



    public CertInfo getcertficatesInfo(WxApiConfig config){

        CertInfo certInfo =  new CertInfo();

        try{


            log.info("获取平台证书");

            WXPayRequest wxPayRequest = new WXPayRequest(config);

            Map<String, String> param = new HashMap<>();
            param.put("mch_id", config.getMchID());
            String nonce_str = WXPayUtil.generateNonceStr();
            param.put("nonce_str", nonce_str);
            param.put("sign_type", "HMAC-SHA256");

            log.info("请求参数："+param);

            String xml = WXPayUtil.generateSignedXml(param, config.getKey(),WXPayConstants.SignType.HMACSHA256);

            String result = wxPayRequest.requestOnce(domain, urlSuffix, nonce_str, xml, 8000, 6000, false);
            log.info("请求返回："+result);
            Map<String,String> resultMap = WXPayUtil.xmlToMap(result);

            String return_code = resultMap.get("return_code");

            if("SUCCESS".equals(return_code)){
                String result_code = resultMap.get("result_code");
                if("SUCCESS".equals(result_code)){
                    String certificates = resultMap.get("certificates");

                    JSONObject jsonObject = JSON.parseObject(certificates);

                    JSONArray data = jsonObject.getJSONArray("data");

                    JSONObject c_data = data.getJSONObject(0);

                    String serial_no = c_data.getString("serial_no");

                    certInfo.setSerial_no(serial_no);

                    JSONObject encrypt_certificate = c_data.getJSONObject("encrypt_certificate");


                    String nonce = encrypt_certificate.getString("nonce");
                    String associated_data = encrypt_certificate.getString("associated_data");
                    String ciphertext = encrypt_certificate.getString("ciphertext");

                    certInfo.setNonce(nonce);
                    certInfo.setAssociated_data(associated_data);
                    certInfo.setCipherText(ciphertext);

                    certInfo.setApi3key(config.getSecurityConfig().getApi3Key());

                }
            }


        }catch (Exception e){

            log.error("获取证书序列号失败",e);
        }

        return  certInfo;

    }







}
